#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Descripttion:
# version: 0.0.1
# Author: Wenwei Fu (2516800961@qq.com)
# FilePath: /fastapi_byd/app/api/routes/expert.py
# Create: 2021-01-04 16:37:40
# LastAuthor: Wenwei Fu
# lastTime: 2021-01-10 15:01:42
# --------------------------------------------------------

import uuid
import cv2
import datetime
import ast
from typing import Optional, Any, List
from pydantic import BaseModel
from fastapi import APIRouter, Request, Body, Depends, HTTPException
from app.db.schemas import Traffic_Area, Traffic_Lane, Traffic_Cameras # 区域
from app.db.database import get_db
from app.api.routes.utils import pixel_trans_geo

router = APIRouter()

@router.get("/list", name="查询区域列表", dependencies=[Depends(get_db)])
async def area_list(
    pageNum: Optional[int] = 1,
    pageSize: Optional[int] = 10,
    request: Request=None
):
    query = Traffic_Area.select().order_by(-Traffic_Area.created_at).paginate(pageNum, pageSize).dicts()
    results = [item for item in query]
    count = Traffic_Area.select().count()
    return {
        "code": 200,
        "message": "查询成功",
        "data": {
            "pageNum": pageNum,
            "pageSize": pageSize,
            "total": count,
            "records": results
        }
    }

@router.get("/get_area_list_by_cameraId", name="根据摄像头ID查询区域列表", dependencies=[Depends(get_db)])
async def area_list_by_cameraId(
    camera_id: str,
    request: Request=None
):
    query = Traffic_Area.select().order_by(-Traffic_Area.created_at).where(Traffic_Area.camera_id == camera_id).dicts()
    results = [item for item in query]
    return {
        "code": 200,
        "message": "查询成功",
        "data": results
    }

class Create_Area_Item(BaseModel):
    area_name: str
    area_number: str
    camera_id: str
    area_id: Optional[str] = str(uuid.uuid4())
    pixel_coordinates: Optional[str] = ''
    geo_coordinates: Optional[str] = ''
    event_list: Optional[Any] = []
    props: Optional[str] = ''

@router.post("/create", name="创建区域", dependencies=[Depends(get_db)])
async def create_area(
    Create_Area_Item: Create_Area_Item,
    request: Request = None
):
    results = Create_Area_Item.__dict__

    coor_trans_results = await pixel_trans_geo(results['pixel_coordinates'], results['camera_id'])
    print('coor_trans_results', coor_trans_results)
    results['geo_coordinates'] = coor_trans_results

    query = Traffic_Area.select().where(Traffic_Area.area_id == results['area_id'])

    if query.exists():
        print('已存在')
        update = await update_area(Create_Area_Item)
        return update
    else:
        results['created_at'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        results['updated_at'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        Traffic_Area.create(**results)
        print('创建区域', results)

        return {
            "code": 200,
            "message": "创建成功",
            "data": results
        }

@router.post("/create_many", name="创建多区域", dependencies=[Depends(get_db)])
async def area_create_many(
    Area_Item: List[Create_Area_Item],
    request: Request = None
):
    results = []
    for item in Area_Item:
        item = item.__dict__
        item['created_at'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        item['updated_at'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        results.append(item)

    Traffic_Area.insert_many(results).execute()
    print('创建区域', results)

    return {
        "code": 200,
        "message": "创建成功",
        "data": results
    }

class Update_Area_Item(BaseModel):
    area_id: str
    area_name: str
    area_number: str
    camera_id: str
    pixel_coordinates: Optional[str] = ''
    geo_coordinates: Optional[str] = ''
    event_list: Optional[Any] = []
    props: Optional[str] = ''

@router.put("/update", name="更新区域", dependencies=[Depends(get_db)])
async def update_area(
    Update_Area_Item: Update_Area_Item,
    request: Request = None
):
    results = Update_Area_Item.__dict__

    print('更新数据：', results)

    updatesql = (Traffic_Area.update(
                    area_name=results['area_name'],
                    area_number=int(results['area_number']),
                    camera_id=results['camera_id'],
                    pixel_coordinates=results['pixel_coordinates'],
                    geo_coordinates=results['geo_coordinates'],
                    event_list=results['event_list'],
                    updated_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                ).where(Traffic_Area.area_id == results['area_id']).execute())

    if updatesql == 1:
        return {
                "code": 200,
                "message": "更新成功",
                "data": {
                    "area_id": results['area_id'],
                    "area_name": results['area_name']
                }
            }
    else:
        return {
                "code": 201,
                "message": "更新失败",
                "data": {
                    "area_id": results['area_id'],
                    "area_name": results['area_name']
                }
            }

@router.put("/update_shape", name="更新区域 shape", dependencies=[Depends(get_db)])
async def update_area_shape(
    area_id: str,
    shape: str,
    request: Request = None
):
    updatesql = (Traffic_Area.update(
                    pixel_coordinates=shape,
                    updated_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                ).where(Traffic_Area.area_id == area_id).execute())
    print('更新 shape：', updatesql)
    if updatesql == 1:
        return {
                "code": 200,
                "message": "更新成功",
                "data": {
                    "area_id": area_id,
                    "shape": shape
                }
            }
    else:
        return {
                "code": 201,
                "message": "更新失败",
                "data": {
                    "area_id": area_id,
                    "shape": shape
                }
            }

@router.delete("/delete", name="删除区域", dependencies=[Depends(get_db)])
async def delete_area(
    id: str,
    request: Request=None
):
    query = Traffic_Area.delete().where(Traffic_Area.id == id).execute()
    if query == 1:
        return {
            "code": 200,
            "message": "删除成功",
            "data": {
                "id": id
            }
        }
    else:
        return {
            "code": 200,
            "message": "删除失败",
            "data": {
                "id": id
            }
        }

@router.delete("/delete_by_area_id", name="删除区域", dependencies=[Depends(get_db)])
async def delete_area(
    area_id: str,
    request: Request=None
):
    query = Traffic_Area.delete().where(Traffic_Area.area_id == area_id).execute()
    if query == 1:
        return {
            "code": 200,
            "message": "删除成功",
            "data": {
                "area_id": area_id
            }
        }
    else:
        return {
            "code": 200,
            "message": "删除失败",
            "data": {
                "area_id": area_id
            }
        }